package com.qianda.qdminiapp.config;

import com.qianda.qdminiapp.security.*;
import com.sun.org.apache.xerces.internal.parsers.SecurityConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.StrictHttpFirewall;
import org.springframework.web.cors.CorsConfiguration;

import java.util.Arrays;

/**
 * @ClassName SecurityConfig
 * @Author cw
 * @Date 2019/8/6 15:30
 * @Version 1.0
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private static final Logger LOG = LoggerFactory.getLogger(SecurityConfiguration.class);

    @Autowired(required = false)
    private UserDetailsService userDetailsService;

    @Bean
    public TokenManager tokenManager() {
        return new InMemoryTokenManager(2592000);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        TokenManager tokenManager = tokenManager();

        http
                .csrf().disable()
                .cors().configurationSource(req -> {
            CorsConfiguration cfg = new CorsConfiguration();
        //    cfg.setAllowCredentials(true);
            cfg.setExposedHeaders(Arrays.asList("Token"));
            cfg.setAllowedHeaders(Arrays.asList(CorsConfiguration.ALL));
            cfg.setAllowedMethods(Arrays.asList("GET", "POST"));
            cfg.setAllowedOrigins(Arrays.asList(CorsConfiguration.ALL));
            cfg.setMaxAge(1800L);
            return cfg;
        })

                .and()
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .antMatchers("/login/**").permitAll()
                .antMatchers("/remote/v1/**").permitAll()
                .antMatchers("/qqd-user/bindPhone").permitAll()
                .antMatchers("/qqd-store/getStores").permitAll()
                .antMatchers("/wxpay/wxPayNotify").permitAll()
                .antMatchers("/wxpay/wxRefundNotify").permitAll()
                .antMatchers("/qqd-store/getStoresByLatAndLnt").permitAll()
                .antMatchers("/test/*").permitAll()
                .antMatchers("/qqd-device/findSign").permitAll()
              //  .antMatchers("/orderRefund/orderRefundBith").permitAll()
                .antMatchers("/qqd-redpacket-activity/**").permitAll()

                // .antMatchers("/socket/**").permitAll()
                .anyRequest().authenticated()
                .and()
                // 用于登录`
                .addFilterBefore(
                        new LoginFilter(authenticationManager(), tokenManager), UsernamePasswordAuthenticationFilter.class)
                // 用于检查令牌
                .addFilterBefore(
                        new AuthenticationFilter(tokenManager), UsernamePasswordAuthenticationFilter.class)

                // 登出处理
                .logout()
                .addLogoutHandler(new LogoutTokenHandler(tokenManager))
                .logoutSuccessHandler(new LogoutSuccessResultHandler())

                .and()
                // 安全框架不会主动创建会话也不会利用会话获取安全上下文
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

//        http.csrf().disable()
//                .cors().configurationSource(req -> {
//            CorsConfiguration cfg = new CorsConfiguration();
//            cfg.setAllowCredentials(false);
//            cfg.setExposedHeaders(Arrays.asList("Token"));
//            cfg.setAllowedHeaders(Arrays.asList(CorsConfiguration.ALL));
//            cfg.setAllowedMethods(Arrays.asList("GET", "POST"));
//            cfg.setAllowedOrigins(Arrays.asList(CorsConfiguration.ALL));
//            cfg.setMaxAge(1800L);
//            return cfg;
//        })
//                .and()
//                .authorizeRequests()
//                .antMatchers("/login").permitAll()
//                .anyRequest().authenticated()
//                .and()
//                .addFilterBefore(
//                        new LoginFilter(authenticationManager(),tokenManager), UsernamePasswordAuthenticationFilter.class)
//
//        ;

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 如果不存在自定义的用户服务则使用默认的
        auth.authenticationProvider(
                new AuthenticationProvider(userDetailsService, PasswordUtils.encoder()));
    }
    // 避免自动配置
    @Bean
    public AuthenticationManager authenticationManager1() throws Exception {
        return authenticationManager();
    }
}
